<template>
  <!-- 头像和身份提示 -->
  <div class="user-profile">
    <img :src="avatarUrl" alt="User Avatar" class="avatar" @click="openFilePicker"/>
    <input type="file" ref="fileInput" style="display: none;" @change="handleFileUpload">
    <div class="user-info">
      <p>学号：{{ studentNumber }}</p>
      <p>身份：{{ identityType }}</p>
    </div>
  </div>

  <div class="myprofile">
    <!-- 基本信息表单 -->
    <div class="profile-form">
      <form>
        <div class="form-group">
          <label for="nickname">用户名：</label>
          <input type="text" id="nickname" v-model="nickname">
        </div>
        <div class="form-group">
          <label for="realname">真实姓名：</label>
          <input type="text" id="realName" v-model="realName">
        </div>
        <div class="form-group">
          <label for="email">常用邮箱：</label>
          <template v-if="!isEditingEmail">
            <span>{{ email }}</span>
            <div class="modify-button" @click="toggleEditing('email')">修改邮箱</div>
          </template>
          <template v-else>
            <input type="email" id="email" v-model="editedEmail">
            <div class="modify-button" @click="saveEmail">确定</div>
            <div class="modify-button" @click="cancelEditing('email')">取消</div>
          </template>
        </div>
        <div class="form-group">
          <label for="phone">手机账号：</label>
          <template v-if="!isEditingPhone">
            <span>{{ phone }}</span>
            <div class="modify-button" @click="toggleEditing('phone')">修改电话</div>
          </template>
          <template v-else>
            <input type="text" id="phone" v-model="editedPhone">
            <div class="modify-button" @click="savePhone">确定</div>
            <div class="modify-button" @click="cancelEditing('phone')">取消</div>
          </template>
        </div>

        <div class="form-group">
          <label>性别：</label>
          <div class="input-wrapper">
            <div class="radio-group">
              <label class="radio-button">
                <input type="radio" v-model="gender" value="男">
                <span class="radio-custom"></span>
                男
              </label>
              <label class="radio-button">
                <input type="radio" v-model="gender" value="女">
                <span class="radio-custom"></span>
                女
              </label>
            </div>
          </div>
        </div>

        <div class="form-group">
          <label>身份类型：</label>
          <label>{{ identityType }}</label>
        </div>
        <div class="form-group">
          <label for="school">学校：</label>
          <input type="text" id="school" v-model="school">
        </div>
        <div class="form-group">
          <label for="bio">个人简历：</label>
          <textarea id="bio" v-model="bio" class="textareasize"></textarea>
        </div>
        <div class="form-group">
          <button type="button" @click="updateProfile">保存</button>
        </div>
      </form>
    </div>
  </div>
</template>
<script>
import axios from 'axios';

export default {
  name: 'ProfilePage',
  data() {
    return {
      avatarUrl:'', // 默认头像路径，根据实际情况修改
      studentNumber: '',
      nickname: '',
      email: '',
      phone: '',
      realName: '',
      gender: '',
      identityType: '',
      school: '',
      bio: '',
      isEditingEmail: false,
      isEditingPhone: false,
      editedEmail: '',
      editedPhone: '',
      dialogType: '',

    };
  },
  mounted() {
    this.fetchStudentInfo();
  },
  methods: {

    async fetchStudentInfo() {
      try {
        const userid = localStorage.getItem("userid");
        const response = await axios.get('http://8.138.12.59:1999/student/showinfo', {
          params: {
            user_id: userid, // 根据实际情况传入用户ID
         
          },
        });
        const data = response.data.data;
        this.avatarUrl = data.img_url;
        this.studentNumber = data.stu_number;
        this.nickname = data.nickname;
        this.email = data.email;
        this.phone = data.phone_num; // 注意接口返回的字段名为 phone_num
        this.realName = data.username;
        this.gender = data.gender;
        this.identityType = data.user_type;
        console.log('Response data:', response.data);
        console.log('Response data:', response.data);
         // 根据英文身份类型转换为中文描述
    if (data.user_type === 'teacher') {
      this.identityType = '老师';
    } else if (data.user_type === 'student') {
      this.identityType = '学生';
    } else {
      this.identityType = data.user_type; // 其他情况保持原始英文身份类型
    }
        this.school = data.university_name;
        this.bio = data.user_intro;
      } catch (error) {
        console.error('Error fetching student info:', error);
      }
    },
    toggleEditing(field) {
    if (field === 'email') {
      this.isEditingEmail = true;
      this.editedEmail = this.email; // 将当前邮箱值赋给编辑变量
    } else if (field === 'phone') {
      this.isEditingPhone = true;
      this.editedPhone = this.phone; // 将当前电话值赋给编辑变量
    }
  },
  cancelEditing(field) {
    if (field === 'email') {
      this.isEditingEmail = false;
      this.editedEmail = ''; // 取消编辑时清空编辑变量
    } else if (field === 'phone') {
      this.isEditingPhone = false;
      this.editedPhone = ''; // 取消编辑时清空编辑变量
    }
  },
  async saveEmail() {
    try {
      const userid = localStorage.getItem("userid");
      const response = await axios.put('http://8.138.12.59:1999/student/updateinfo', {
        user_id: userid, // 替换成真实的用户ID
        email: this.editedEmail,
        // 其他参数按需添加，这里只演示了修改邮箱的请求
      });
      console.log('hhhhhhhh:', this.editedEmail);
      if (response.data.status === 1) {
      // Assuming 'data' contains user information
      if (response.data.data && response.data.data.email !== null) {
        this.email = response.data.data.email;
        this.isEditingEmail = false;
        console.log('Email updated successfully:', this.email);
      } else {
        console.error('Failed to update email: Updated email is null');
      }
    } else {
      console.error('Failed to update email:', response.data.msg);
    }
    } catch (error) {
      console.error('Error updating email:', error);
      // 可以在界面上显示详细错误信息
    }
  },
  async savePhone() {
    try {
      const userid = localStorage.getItem("userid");
      const response = await axios.put('http://8.138.12.59:1999/student/updateinfo', {
        user_id: userid, // 替换成真实的用户ID
        phone_num: this.editedPhone,
        // 其他参数按需添加，这里只演示了修改电话的请求
      });
      console.log('ggggggg:', this.editedPhone);
      if (response.data.status === 1) {
        if (response.data.data && response.data.data.phone_num !== null){
          this.phone = response.data.data.phone_num; // 更新成功后更新本地数据
        this.isEditingPhone = false; // 关闭编辑模式
        console.log('Phone number updated successfully:', this.phone);
        }else {
        console.error('Failed to update email: Updated email is null');
      }
      } else {
        console.error('Failed to update phone number:', response.data.message);
        // 可以在界面上显示详细错误信息
      }
    } catch (error) {
      console.error('Error updating phone number:', error);
      // 可以在界面上显示详细错误信息
    }
  }, 
  openFilePicker() {
    // 手动触发文件选择框
    this.$refs.fileInput.value = null; // 重置input，确保change事件每次都触发
    this.$refs.fileInput.click();
  },
  async handleFileUpload(event) {
    const userid = localStorage.getItem("userid");
    const file = event.target.files[0];
      const formData = new FormData();
      formData.append('file', file);
      formData.append('user_id', userid); // 将用户ID添加到FormData中
      const config = {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  };
    // 调用后端接口进行头像上传
  try {
    const response = await axios.post('http://8.138.12.59:1999/student/updateAvatar', formData, config);
    this.avatarUrl = response.data.data; // 注意这里根据实际返回的数据结构获取头像地址
          console.log('Avatar URL:', this.avatarUrl);
  } catch (error) {
    console.error('头像上传失败:', error);
    // 处理上传失败的逻辑，例如给用户提示或记录错误日志
  }
},
  async updateProfile() {
  this.isUpdating = true;
  try {
    const userid = localStorage.getItem("userid");
    const response = await axios.put('http://8.138.12.59:1999/student/updateinfo', {
      user_id: userid, // 根据实际情况传入用户ID  
      img_url: this.avatarUrl,
      nickname: this.nickname,
      email: this.email,
      phone_num: this.phone,
      username: this.realName,
      gender: this.gender,
      university_name: this.school,
      user_intro: this.bio,
      // 可根据需要添加其他字段
    });

    
     // 更新本地数据之前进行空值检查
     const updatedData = response.data.data || {}; // 如果 response.data.data 为 null 或 undefined，则使用空对象
     this.avatarUrl = updatedData.img_url || ''; // 如果 img_url 为 null 或 undefined，则使用空字符串
    this.nickname = updatedData.nickname || '';
    this.realName = updatedData.username || '';
    this.gender = updatedData.gender || '';
    this.school = updatedData.university_name || '';
    this.bio = updatedData.user_intro || '';

    console.log('Profile updated successfully:', response.data.message);
    console.log('Response data:', response.data);
  } catch (error) {
    console.error('Error updating profile:', error);
    if (error.response) {
      console.error('Server Error Status:', error.response.status);
      console.error('Server Error Data:', error.response.data);
    }
    // 在这里可以添加适当的错误处理逻辑，例如显示用户友好的错误提示
  } finally {
    this.isUpdating = false;
  }
},
  },
};
</script>


<style scoped>
/* 用户信息样式 */
.user-profile {
  display: flex;
  align-items: center;
  padding: 20px;
  background-size: cover;
  /* 背景图尺寸适应容器 */
  background-image: url('@/assets/mycourse-bg.png');
}

.avatar {
  width: 70px;
  height: 70px;
  border-radius: 50%;
  margin-left: 150px;
}

.user-info {
  margin-left: 20px;
  text-align: left;
}

p{
  color: #000;
}

.myprofile {
  display: flex;
  width: 58.4%;
  margin-left: 150px;
  background-color: #f9f9f9;
  padding: 5px 150px 20px 150px;
}

.main-content {
  flex: 5;
  background-color: #ffffff;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}


.profile {
  display: flex;
  flex-direction: column;
  justify-content: center;
}

/* .profile-header {
  margin-left: 200px;
  width: 1920px;
  height: 140px;
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  background-size: cover; 
  background-image: url('@/assets/bg_Profile.png');
}
.profile-header img {
  width: 100px; 
  height: 100px;
  border-radius: 50%;
  object-fit: cover; 
  margin-right: 20px; 
}
.profile-header .identity {
  margin-left: 20px;
} */

.profile-form {
  width: 800px;
  flex-wrap: wrap;
  justify-content: center;
  background-color: white;
  padding: 40px;
  border: 1px solid #ccc;
  border-radius: 5px;
  margin-right: auto;
  margin-left: auto;

}

.form-group {
  margin-bottom: 25px;
  padding-left: 0%;
  display: flex;

}

.form-group label {
  width: 110px;
  margin-right: 10px;
  text-align: left;
  line-height: 32px;
  /* 垂直居中标签文字 */
}

.textareasize {
  resize: none;
  width: 650px;
  /* 设置文本框宽度 */
  height: 96px;
  /* 设置文本框高度 */
}

input[type="text"],
input[type="email"],
select,
textarea {
  width: calc(100% - 500px);
  border: 1px solid #ccc;
  border-radius: 3px;
  box-sizing: border-box;
}

.input-wrapper {
  display: flex;
  width: calc(100% - 100px);
  /* 定义选择框的宽度 */
}

.radio-group {
  display: flex;
}

.radio-button {
  display: flex;
  align-items: center;
  margin-right: 10px;
  cursor: pointer;
}

.radio-button1 {
  display: flex;
  align-items: center;
  margin-right: 10px;
  cursor: pointer;
}

.radio-button input[type="radio"] {
  display: none;
  /* 隐藏原生的单选框 */
}

.radio-button1 input[type="radio"] {
  display: none;
  /* 隐藏原生的单选框 */
}

.radio-custom {
  display: inline-block;
  width: 15px;
  height: 15px;
  background-color: transparent;
  transition: background-color 0.3s, color 0.3s;
  border-radius: 50%;
  /* 圆形按钮 */
  border: 3px solid #ccc;
  margin-right: 5px;
}

.radio-button input[type="radio"]:checked+.radio-custom {
  background-color: rgb(59, 150, 255);
  color: white;
}

.radio-button1 input[type="radio"]:checked+.radio-custom {
  background-color: gray;
  color: white;
}


button {
  padding: 10px 20px;
  background-color: #007bff;
  color: #fff;
  border: none;
  border-radius: 3px;
  cursor: pointer;
}

button:hover {
  background-color: #0056b3;
}

.modify-button {
  margin-left: 10px;
  color: #007bff;
}

/* 弹窗 */
.dialog {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
}

.dialog-content {
  background-color: white;
  padding: 20px;
  border-radius: 5px;
}

.dialog-content h2 {
  margin-bottom: 10px;
}

.dialog-content input {
  margin-bottom: 10px;
  width: 100%;
  padding: 5px;
  box-sizing: border-box;
}

.dialog-content button {
  margin-right: 10px;
}
</style>